import { _decorator, BlockInputEvents, BoxCollider2D, CircleCollider2D, Collider2D, color, Color, Component, director, ERigidBody2DType, instantiate, Material, math, Node, PolygonCollider2D, Prefab, Rect, RigidBody2D, Sprite, UIRenderer, UITransform, Vec3, Vec4, view } from 'cc';
import { HoleAction } from './HoleAction';
import { PinAction } from './PinAction';
import { Global } from './Global';
import { events } from './Enums';
import AssetMgr from '../frame/AssetMgr';
import { SortNodeHierarchy } from './SortNodeHierarchy';
import { objPool } from './fish/objPool';
const { ccclass, property } = _decorator;

@ccclass('ElementAction')
export class ElementAction extends Component {

    is_enabled = false;

    onLoad() {
        director.on(events.objpool_pin, this.removeAllPin, this)

        director.on(events.remove_board, this.setBlocks, this)

        /** --->测试 */
        this.node.getComponent(RigidBody2D).type = ERigidBody2DType.Static;
    }

    // cur_color:ColorDate = null;
    start() {

        //--->改 (不需要 BlockInputEvent 组件了)
        this.setBlocks(false);
    }

    update(deltaTime: number) {
        let currentPosition = this.node.getPosition()
        if (currentPosition.y < - view.getVisibleSize().height / 2) {
            this.node.removeFromParent();
            director.emit(events.update_element, this);
        }
    }

    public get_hole_num(): number {
        let hole_num: number = 0;
        this.node.children.forEach(element => {
            if (element.getComponent(HoleAction)) {
                hole_num++;
            }
        });
        return hole_num;
    }

    /** 显示轮廓 */
    show_outline() {
        this.node.getChildByName('img').active = false;
        this.node.getChildByName('imgBorder').getComponent(Sprite).color = Color.GRAY;

        // const pin = this.node.getComponentsInChildren(PinAction)
        // for (let i = 0; i < pin.length; i++) {
        //     pin[i].onShow(false);
        // }

        let pins_act: PinAction[] = [];
        this.get_pin_color(pins_act);
        pins_act.forEach(pin => {
            pin.onShow(false)
        });
    }
    /** 显示 */
    show_node() {
        this.node.getChildByName('img').active = true;
        this.node.getChildByName('imgBorder').getComponent(Sprite).color = Color.WHITE;

        //  const pin = this.node.getComponentsInChildren(PinAction)
        // for (let i = 0; i < pin.length; i++) {
        //     pin[i].onShow(true);
        // }

        let pins_act: PinAction[] = [];
        this.get_pin_color(pins_act);
        pins_act.forEach(pin => {
            pin.onShow(true)
        });
    }


    // onEnable() {
    //     this.node.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic;
    // }

    // onDisable(){
    //     this.node.getComponent(RigidBody2D).type = ERigidBody2DType.Static;

    // }

    onDestroy() {
        director.off(events.remove_board, this.setBlocks, this)
    }

    //1 初始化板子
    public init_element(group_id: number, ele_color: any) {
        this.node.getComponent(RigidBody2D).group = group_id;
        // this.node.getComponent(BoxCollider2D).group = group_id;
        // this.node.getComponent(CircleCollider2D).group = group_id;
        this.node.getComponent(PolygonCollider2D).group = group_id;

        // this.node.getComponents(BoxCollider2D).forEach(element => {
        //     element.group = group_id;
        // });
        // this.node.getComponents(CircleCollider2D).forEach(element => {
        //     element.group = group_id;
        // });
        // this.node.getComponents(PolygonCollider2D).forEach(element => {
        //     element.group = group_id;
        // });

        //set img color
        // this.cur_color = ele_color;
        this.node.children.forEach(element => {
            if (element.name === "img") {
                let img = element.getComponent(Sprite);
                //console.log("板子颜色：",ele_color)
                img.color = color(ele_color.color)//new Color(ele_color.r, ele_color.g, ele_color.b, 190);
            }
            else if (element.name === "Img") {//先留着
                if (element.children.length > 0) {
                    let img = element.getChildByName("img").getComponent(Sprite);
                    img.color = color(ele_color.color)
                }

            }
        });
        // console.log("ele: ",group_id)

        let sortNode = this.node.getComponent(SortNodeHierarchy)
        if (!sortNode)
            sortNode = this.node.addComponent(SortNodeHierarchy)

        sortNode.on_posY_sort("hole")
    }

    //2 生成电池
    public init_pin(group_id: number, color_pin_arr: any[]) {
        //获取 hole
        this.node.children.forEach(async _hole => {
            if (_hole.getComponent(HoleAction)) {
                //对象池加载
                // let prefab = await AssetMgr.Inst.getOnePrefab("prefabs/game/battery" , "gameBundle");
                // let new_pin = instantiate(prefab);
                let new_pin = objPool.ins.getObj("battery")
                this.node.addChild(new_pin);

                //设置电池位置
                let pos = _hole.getPosition();
                pos.y += Global.offoset_y;
                new_pin.setPosition(pos);
                new_pin.getComponent(PinAction).init_date(group_id, color_pin_arr.shift());
                // console.log("pin: ",group_id)

                new_pin.getChildByName('battery_img').setWorldRotation(math.quat(0, 0, 0, 1))

                let pins_act: PinAction[] = [];
                this.get_pin_color(pins_act);
                pins_act.push(new_pin.getComponent(PinAction));


            }
        });


        // this.scheduleOnce(()=>{
        //     this.enabled_rig()
        // },0.5)
    }

    removeAllPin() {
        console.log("回收对象")
        let pins_act: PinAction[] = [];
        this.get_pin_color(pins_act);
        for (let i = 0; i < pins_act.length; i++) {
            const obj = pins_act[i].node;
            objPool.ins.removeObj("battery", obj)
        }
    }

    enabled_rig() {
        if (this.is_enabled) return;
        this.is_enabled = true;

        //启用刚体
        this.node.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic;
    }

    get_pin_color(arr: PinAction[]) {
        this.node.children.forEach(pin_node => {
            let pin_action = pin_node.getComponent(PinAction)
            if (pin_action && pin_action.pin_color) {
                arr.push(pin_node.getComponent(PinAction));
            }
        });

    }

    setBlocks(enabled: boolean) {
        this.node.children.forEach(child => {
            const _block = child.getComponent(BlockInputEvents);
            if (_block) {
                // if(child.name != Global.hole_node_name)
                _block.enabled = enabled
            }
        })

    }
}

